package com.wawj.compplugin.utils

class GitUtil {

    private static def userName
    private static def password

    static setGitCredentials(String userName, String password) {
        this.userName = userName.replace("@", "%40")
        this.password = password
    }

    static boolean isGitDir(File dir) {
        return new File(dir, ".git").exists()
    }
/**
 * 从git utl截取最后一部分为仓库名
 * @param gitUrl
 * @param firstLetterUpper 截取后首字母大写
 * @return
 */
    static String cutRepoName(String gitUrl, boolean firstLetterUpper) {
        gitUrl = gitUrl.substring(gitUrl.lastIndexOf("/") + 1, gitUrl.lastIndexOf("."))
        if (firstLetterUpper) {
            gitUrl = gitUrl.substring(0, 1).toUpperCase() + gitUrl.substring(1);
        }
        return gitUrl
    }

    static String getOriginRemoteFetchUrl(File dir) {
        def process = ("git remote -v").execute(null, dir)
        def result = process.waitFor()
        if (result != 0) {
            throw new RuntimeException("[repo] - failure to execute git command [git remote -v] under ${dir.absolutePath}\n message  ${process.err.text}")
        }

        def url = null
        process.getText().readLines().each {
            if (it.startsWith('origin') && it.endsWith('(fetch)')) {
                url = it.replace('origin', '').replace('(fetch)', '').trim()
            }
        }
        return url
    }

    //get Cur branch
    static String curBranch() {
        return CmdUtil.executeForOutput("git rev-parse --abbrev-ref HEAD", null, false)
                .replace("\n", "")
    }

    static String curBranchName(File dir) {
        return CmdUtil.executeForOutput("git rev-parse --abbrev-ref HEAD", dir)
                .replace("\n", "")
    }

    static Boolean clone(File dir, String gitUrl) {
        if (userName != null) {
            StringBuilder gitUrlStr = new StringBuilder(gitUrl)
            gitUrl = gitUrlStr.insert(gitUrlStr.indexOf("://"), userName + ":" + password + "@")
        }
        return CmdUtil.execute("git clone ${gitUrl} -l ${dir}", null, true)
    }

    static Boolean clone(File dir, String gitUrl, String branch) {
        return CmdUtil.execute("git clone $gitUrl -l $dir -b $branch", null, true)
    }

    static Boolean forcePull(File dir, String branch) {
        return CmdUtil.execute("git pull --force origin $branch:$branch", dir, true)
    }

    static Boolean isClean(File dir) {
        return CmdUtil.executeForOutput("git status -s", dir).trim() == "";
    }

    static String fileStatus(File dir) {
        return CmdUtil.executeForOutput("git status -s ", dir)
    }

    static Boolean isLocalBranch(File dir, String branch) {
        return new File(dir, ".git/refs/heads/$branch").exists()
    }

    static Boolean isBranchChanged(File dir, String branch) {
        return curBranchName(dir) != branch
    }

    static checkoutBranch(File dir, String branch) {
        CmdUtil.execute("git checkout ${branch}", dir)
    }

    static checkoutRemoteBranch(File dir, String branch) {
        CmdUtil.execute("git checkout -b $branch origin/$branch", dir)
    }

    static checkoutNewBranch(File dir, String branch) {
        CmdUtil.execute("git checkout -b $branch", dir)
    }

    static Boolean isRemoteBranch(File dir, String branch) {
        CmdUtil.execute("git fetch", dir)
        def text = CmdUtil.executeForOutput("git branch -r")
        return text.contains("origin/$branch")
    }

    static Boolean isLocalExistBranch(File dir, String branch) {
        return new File(dir, ".git/refs/heads/$branch").exists()
    }

    static Boolean pullRebase(File dir) {
        return CmdUtil.execute("git pull --rebase", dir, false)
    }

}
